package com.hnevc.foodserver.service;

import com.hnevc.foodserver.bean.UpdatePWDVo;
import com.hnevc.foodserver.bean.Users;
import com.hnevc.foodserver.dao.UsersDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UsersService {
    @Autowired
    UsersDao usersDao;

    public Users login(Users users) {
        Users users1 = usersDao.findOne(Example.of(users)).orElse(null);
        return users1;
    }

    public Users register(Users users) {
        List<Users> all = usersDao.findAll(Example.of(users));
        // 如果存在同名用户，则返回注册失败；否则返回注册用户信息
        if(all!=null && all.size()>0) {
            return  null;
        }else{
            Users save = usersDao.save(users);
            return save;
        }

    }

    public Users updateHeadPic(Integer id, String s) {
        Users one = usersDao.getOne(id);
        one.setIcon(s);
        Users users = usersDao.saveAndFlush(one);
        return users;
    }

    public List<Users> list() {
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        return usersDao.findAll(sort);
    }

    public Users update(Users users) {

        return usersDao.save(users);

    }
    public Page<Users> listByPage(PageRequest pageRequest){
        return usersDao.findAll(pageRequest);
    }
    public Users updatepwd(UpdatePWDVo users) {
        Users user1 = new Users();
        user1.setUsername(users.getUsername());
        user1.setPassword(users.getPassword());
        Users users2 = usersDao.findOne(Example.of(user1)).orElse(null);
        if (users2 != null) {
            users2.setPassword(users.getNewPassword());
            return usersDao.save(users2);
        }
        return null;
    }
}
